//
//  MZYsearchViewController.m
//  WristWatch
//
//  Created by dllo on 15/11/2.
//  Copyright (c) 2015年 dllo. All rights reserved.
//

#import "MZYsearchViewController.h"
#import "MZYHeader.h"
#import "MZYsearchModel.h"
#import "MZYbrandinfoViewController.h"
#import "MZYthirdViewController.h"

@interface MZYsearchViewController ()<UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate>
@property(nonatomic, retain)UISearchBar *searchBar;
@property(nonatomic, retain)UITableView *tableView;

@property (nonatomic, retain) NSMutableArray *dataArr;

@property (nonatomic, retain) NSMutableArray *mainArr;//数据源

@property (nonatomic, copy) NSString *str;

@property (nonatomic, assign) NSInteger page;

@property (nonatomic, assign) NSInteger maxPageId;

@end

@implementation MZYsearchViewController

- (void)dealloc {
    [_searchBar release];
    [_tableView release];
    [_dataArr release];
    [_mainArr release];
    [_str release];
    
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.tableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    self.tableView.rowHeight = 100;
    [self.tableView release];
    
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.backgroundColor = [UIColor whiteColor];
    
    [self searchBarCreataData];

}

#pragma mark UISearchBar的创建
- (void)searchBarCreataData {
    self.searchBar = [[[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 64)] autorelease];
    
    self.navigationItem.titleView = self.searchBar;
    [self.searchBar becomeFirstResponder];
    
    // 搜索框的占位符
    [self.searchBar setPlaceholder:@"搜索..."];
    // 搜索框样式
    [self.searchBar setBarStyle:UIBarStyleBlackTranslucent];
    // 搜索框的颜色，当设置此属性时，barStyle将失效
    [self.searchBar setTintColor:[UIColor colorWithRed:3 / 255.0 green:100 / 255.0 blue:255 / 255.0 alpha:1]];
    // 设置是否透明
    [self.searchBar setTranslucent:YES];
    
    self.searchBar.searchBarStyle = UISearchBarStyleProminent;
     //设置搜索范围
     self.searchBar.showsScopeBar = YES;

    [self.view addSubview:self.searchBar];
    // 设置搜索框中文本框的背景
    //    [self.searchBar setSearchFieldBackgroundImage:[UIImage imageNamed:@"1.png"]forState:UIControlStateNormal];
    [self.searchBar setSearchResultsButtonSelected:NO];// 设置搜索结果按钮是否选中
    
//    [self.searchBar setShowsSearchResultsButton:YES];// 是否显示搜索结果按钮

    // 是否显示取消按钮
    [self.searchBar setShowsCancelButton:YES animated:NO];
    
    [self.searchBar setKeyboardType:UIKeyboardTypeEmailAddress];// 设置键盘样式

    
    
    self.searchBar.delegate = self;
    [self.searchBar sizeToFit];
    
//    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"11"] style:UIBarButtonItemStylePlain target:self action:@selector(click:)];
    
}

//- (void)click:(UIBarButtonItem *)button {
//    MZYBrandViewController *brand = [[MZYBrandViewController alloc] init];
//    [self.navigationController presentViewController:brand animated:YES completion:^{
//        
//    }];
//}

-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    //放弃第一响应者对象，关闭软键盘
    [self.searchBar resignFirstResponder];
}

// 键盘搜索按钮按下时调用
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    [self.searchBar resignFirstResponder];
    NSString *strPath = [[NSMutableString stringWithFormat:@"http://h5.ttime.com/ajax/mall/find/ALL/0/0/asc?token=c16f1e396a23381d3f48a067338f1f06&cityid=2&scontent=%@&v=2.2.6&from=l_scrent&flag=app", self.searchBar.text] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding].mutableCopy;
    NSLog(@"%@", strPath);
    [self getDataByWeb:strPath];    // 解析数据的方法
    
    
}


- (void)getDataByWeb:(NSString *)urlStr{
    self.dataArr = [NSMutableArray array];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:urlStr parameters:self success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic = responseObject;
        self.dataArr = [NSMutableArray array];
        [self.tableView reloadData];
        if ([dic[@"result"][@"products"] count] != 0) {
            self.dataArr = [MZYsearchModel MZYBaseModelByArr:dic[@"result"][@"products"]];
            NSLog(@"%@", self.dataArr);
            [self.tableView reloadData];
        }
        else if([dic[@"result"][@"products"] count] == 0){
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示:" message:@"未找到您要搜索的内容..." delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
            [alert release];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
    
}




- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *reuse = @"reuse";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
    if (!cell) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuse] autorelease];
    }
    // 关闭点击效果
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    // 引出model接收数组信息
    MZYsearchModel *model = self.dataArr[indexPath.row];
    cell.textLabel.text = model.name;
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    

    // 高亮
    NSMutableAttributedString *heightLightStr = [[NSMutableAttributedString alloc] initWithString:model.name];
    
    for (NSInteger i = 0; i < [model.name length]; i++) {
        NSString *str = [model.name substringWithRange:NSMakeRange(i, 1)];
        if ([self.searchBar.text containsString:str]) {
            // 高亮
            [heightLightStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(i, 1)];
            
        }
    }
    [cell.textLabel setAttributedText:heightLightStr];
    [heightLightStr release];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    MZYthirdViewController *brandVC = [[MZYthirdViewController alloc] init];

    MZYsearchModel *model = self.dataArr[indexPath.row];
    NSLog(@"111111%@",model.url);
    MZYstyleModel *stylemodel = [MZYstyleModel new];
    stylemodel.product_id = model.url;
    brandVC.style = stylemodel;
    [stylemodel release];
    brandVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:brandVC animated:YES];
    [brandVC release];
    
}


-(void)viewWillDisappear:(BOOL)animated{
    [self.searchBar resignFirstResponder];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
